/*
 * @features: 主要功能
 * @description: 内容说明
 * @Date: 2021-09-24 09:35:42
 * @Author: judu233(769471424@qq.com)
 * @LastEditTime: 2021-10-12 23:26:47
 * @LastEditors: judu233
 */


import c3d from "../../../cc";
import { resLoader } from "../../ResLoader";

const { ccclass, property, menu } = c3d._decorator;

@ccclass("ButtonSimple")
@menu('ui/button/ButtonSimple')
export default class ButtonSimple extends c3d.Component {
    @property({ tooltip: "是否只能触发一次" })
    private once: boolean = false;

    @property({ tooltip: "每次触发间隔" })
    private interval: number = 500;

    @property({ tooltip: "是否开启" })
    disabledEffect: boolean = false;

    private anim!: c3d.Animation;
    private touchCount = 0;
    private touchtEndTime = 0;

    onLoad() {
        this.anim = this.node.addComponent(c3d.Animation);

        var ac_start = resLoader.get("common/anim/button_scale_start", c3d.AnimationClip)!;
        var ac_end = resLoader.get("common/anim/button_scale_end", c3d.AnimationClip)!;
        this.anim.defaultClip = ac_start;
        this.anim.createState(ac_start, ac_start?.name);
        this.anim.createState(ac_end, ac_end?.name);

        this.node.on(c3d.Node.EventType.TOUCH_START, this.onTouchtStart, this);
        this.node.on(c3d.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(c3d.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }

    /** 触摸开始 */
    protected onTouchtStart(event: c3d.EventTouch) {
        if (!this.disabledEffect) {
            this.anim.play("button_scale_start");
        }
    }

    /** 触摸结束 */
    protected onTouchEnd(event: c3d.EventTouch) {
        if (!this.disabledEffect) {
            this.anim.play("button_scale_end");
        }

        if (this.once) {
            if (this.touchCount > 0) {
                event.propagationStopped = true;
                return;
            }
            this.touchCount++;
        }

        // 防连点500毫秒出发一次事件
        if (this.touchtEndTime && c3d.game.totalTime - this.touchtEndTime < this.interval) {
            event.propagationStopped = true;
        }
        else {
            this.touchtEndTime = c3d.game.totalTime;
        }
    }

    onDestroy() {
        this.node.off(c3d.Node.EventType.TOUCH_START, this.onTouchtStart, this);
        this.node.off(c3d.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.off(c3d.Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    }
}
